trendMaker <- function(post, time, newdata){
  l0.boot <- apply( post, 1, function(x) {
    data2 <- data.frame(postdraw = x, time= time)
    if ( nrow(data2) > 6 ){
      m1 <- loess(postdraw ~ time, data=data2)
      return( predict(m1, newdata=newdata) )
      }
    else { 
      m1 <- lm(postdraw ~ time, data=data2)
      return( predict(m1, newdata=newdata) )
      }
    })
  CI.boot <- apply(l0.boot, 1, quantile, probs=c(.025, .5, .975) )
  CI.boot <- data.frame(cbind(t(CI.boot), time=newdata[,"time"]))
  colnames(CI.boot) <- c("L", "M", "U", "time")
  return(CI.boot)
  }


fig_countryprob <- function(countries){
  k <- length(countries)
  if ( k == 10 ) {
    par(mar=c(2,2,2,0.8), oma=c(0,0,0,0), mfrow=c(5,2))
    }
  else { ( k == 15 )
    par(mar=c(2,2,2,0.8), oma=c(0,0,0,0), mfrow=c(5,3))
    }

  for( i in 1:k ){
    selct <- ( mrg.ce$countryname==countries[i] )
    x <- mrg.ce[selct, ]
    newdata <- data.frame( year=seq(min(x$year), max(x$year), by=1))
    postslice <- K1.sampled[,selct]
    time <- mrg.ce[selct, "year"]
    countrytrend <- trendMaker(post=K1.sampled[,selct], 
                  time=mrg.ce[selct, "year"], 
                  newdata=data.frame( 
                    time=seq(min(x$year), max(x$year), by=1))
                    )
      # Generate the figure 
    plot(1,1,ylim=c(0,1), xlim=c(1945,2010), type="n", ylab="", xlab="", main=countries[i], axes=FALSE)
    axis(1)
    axis(2, at=c(0.2,0.5,0.8))
    grid <- seq(0,1,by=0.2)
    for(i in 1:length(grid)){
      abline(h=grid[i], lty=1, lwd=0.25, col=grey(0.9))
      }
    grid <- seq(1950,2000,by=10)
    for(i in 1:length(grid)){
      abline(v=grid[i], lty=1, lwd=0.25, col=grey(0.9))
      }
    abline(h=0.5, lty=2)
    points(x$year, x$K1mu, pch=20)
    lines(countrytrend$time, countrytrend$M, col="black",lwd=2)
    lines(countrytrend$time, countrytrend$L, col=grey(0.55),lwd=2)
    lines(countrytrend$time, countrytrend$U, col=grey(0.55),lwd=2)
    cat(". ")
    }
  }
